export * from "@/components/_utils";

export const isDev = import.meta.env.MODE === "development"; //是否是开发环境，本来应该是'development'，但是package.json中指定了 --mode dev

/**
 * 防抖：指触发事件后在 n 秒内函数只能执行一次，如果在 n 秒内又触发了事件，则会重新计算函数执行时间
 * @param {Function} fn 回调函数
 * @param {Boolean} immediate 是否立即执行
 * @param {Number} delay 延迟时间
 * @example methods: {onSubmit: debounce((event, param) => {console.log("防抖测试");})}
 */
export function debounce(
  fn: (...args: any) => void,
  immediate = true,
  delay = 1000
) {
  let timer: any = null;
  return function (...args: any) {
    if (timer) clearTimeout(timer);
    if (immediate) {
      const canExe = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, delay);
      if (canExe) {
        fn(...args);
      }
    } else {
      timer = setTimeout(() => {
        fn(...args);
        timer = null;
      }, delay);
    }
  };
}

/**
 * 节流：指连续触发事件，但是在 n 秒内只执行一次函数
 * @param {Function} fn 回调函数
 * @param {Boolean} immediate 是否立即执行
 * @param {Number} delay 延迟时间
 * @example methods: {onSubmit: throttle((event, param) => {console.log("节流测试");})}
 */
export function throttle(
  fn: (...args: any) => void,
  immediate = true,
  delay = 1000
) {
  if (immediate) {
    let previous = 0;
    return (...args: any) => {
      const now = Date.now();
      if (now - previous > delay) {
        fn(...args);
        previous = now;
      }
    };
  }
  let timer: any = null;
  return (...args: any) => {
    if (!timer) {
      timer = setTimeout(() => {
        fn(...args);
        timer = null;
      }, delay);
    }
  };
}
